﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EComAssignment.Models;
using EComAssignment.Filter;
using System.Web.Routing;

namespace EComAssignment.Controllers
{
    public class AccountController : Controller
    {
        //
        // GET: /Account/

        public ActionResult Login(string GotoAction, string GotoConntroller)
        {
            if (Session["username"] != null)
            {
                return RedirectToAction("Index2", "Main");
            }
            
            ViewBag.action = GotoAction;
            ViewBag.controller = GotoConntroller;
            return View();
        }
        public ActionResult Logout()
        {
            Session["username"] = null;
            Session["userLevel"] = null;
            Session["accID"] = null;
            return RedirectToAction("Index2", "Main");
        }
        public ActionResult ForgetPassword()
        {
            return View();
        }
        [HttpPost]
        public ActionResult checkLogin(string username, string password)
        {
            string action = Request.Form["action"];
            string controller = Request.Form["controller"];
            Account account = AccountModel.checkLogin(username, password);
            if (account == null)
            {
                ViewBag.errorMsg = "Tên tài khoản hoặc mật khẩu không chính xác";
                ViewBag.action = action;
                ViewBag.controller = controller;
                return View("Login");
            }
            if (account.user_level == 3)
            {
                ViewBag.username = username;
                return View("InactiveAccount");
            }
            Session["username"] = username;
            Session["userLevel"] = account.user_level;
            Session["accID"] = account.ID;
            
            HttpCookie cookie = new HttpCookie("cookiename");            
            if (Request.Form["ckRemember"] != null)
            {
                cookie.Values.Add("username", username);
                cookie.Values.Add("password", password);
                cookie.Expires = DateTime.Now.AddDays(30);
            }
            else
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }                        
            Response.Cookies.Add(cookie);

            if (action != null && controller != null && action.Length > 0 && controller.Length > 0)
            {
                return RedirectToAction(action, controller);
            }
            return RedirectToAction("Index2", "Main");
        }
        [HttpPost]
        public ActionResult SendConfirmResetPassword()
        {
            string username = Request.Form["username"];
            bool result = AccountModel.sendConfirmResetPassword(username, Request.Url.Port);
            ViewBag.nameMsg = "Xác nhận reset mật khẩu";
            if (result)
            {
                ViewBag.bodyMsg = "Xin quý khách vui lòng vào email để xác nhận reset mật khẩu";
            }
            else
            {
                ViewBag.bodyMsg = "Tên tài khoản không tồn tại";
            }
            return View("ShowInfo");
        }
        public ActionResult resetPassword()
        {
            string username = Request.QueryString["username"];
            string id = Request.QueryString["id"];
            AccountModel.resetPassword(username, id, Request.Url.Port);
            ViewBag.nameMsg = "Gửi mật khẩu mới";
            ViewBag.bodyMsg = "Xin quý khách vui lòng vào email để lấy mật khẩu mới";
            return View("ShowInfo");
        }
        public ActionResult sendActiveCode()
        {
            string username = Request.QueryString["username"];
            int port = Request.Url.Port;
            AccountModel.sendActiveCode(username, port);
            ViewBag.nameMsg = "Đã gửi email kích hoạt";
            ViewBag.bodyMsg = "Xin quý khách vui lòng vào email để kích hoạt tài khoản";
            return View("ShowInfo");
        }
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public ActionResult RegisterClick()
        {
            string username = Request.Form["username"];
            string password = Request.Form["password"];
            string fullName = Request.Form["fullName"];
            string email = Request.Form["email"];
            string address = Request.Form["address"];
            string phoneNumber = Request.Form["phone_number"];
            int port = Request.Url.Port;
            bool success = AccountModel.createAccount(username, password, fullName, email, address, phoneNumber, port);
            if (success)
            {
                return RedirectToAction("RegisterSuccess", "Account");
            }

            return RedirectToAction("RegisterFailure", "Account");
        }

        public ActionResult ActiveAccount()
        {
            string id = Request.QueryString["id"];
            string username = Request.QueryString["username"];
            bool success = AccountModel.activeAccount(id, username);
            if (success)
            {
                return View();
            }
            return RedirectToAction("RegisterFailure", "Account");
        }

        public ActionResult RegisterSuccess()
        {
            return View();
        }

        public ActionResult RegisterFailure()
        {
            return View();
        }

        [HttpPost]
        public string isUserExist()
        {
            string user = Request.Form["user"];
            string result = AccountModel.isUserExist(user).ToString();
            return result;
        }
        //private void getCategories2()
        //{
        //    DataClasses1DataContext ctx = new DataClasses1DataContext();
        //    Dictionary<int, IQueryable<string>> list = new Dictionary<int, IQueryable<string>>();
        //    Dictionary<int, string> list2 = new Dictionary<int, string>();
        //    var category = (from c in ctx.Categories
        //                    select new { c.ID, c.name });
        //    foreach (var cate in category)
        //    {
        //        var group = (from p in ctx.Products
        //                     where p.category_ID == cate.ID
        //                     select p.group_name).Distinct();
        //        list.Add(cate.ID, group);
        //        list2.Add(cate.ID, cate.name);
        //    }
        //    ViewBag.categoryList2 = list;
        //    ViewBag.categoryList2Name = list2;
        //}

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult personal()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "Personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            return View();
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult changePassword()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                //RouteValueDictionary data = new RouteValueDictionary();
                ViewBag.action = "changePassword";
                ViewBag.controller = "Account";
                return View("Login");
            }

            return View();
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult changePasswordClick()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                //RouteValueDictionary data = new RouteValueDictionary();
                ViewBag.action = "changePassword";
                ViewBag.controller = "Account";
                return View("Login");
            }

            string oldPass = Request.Form["oldPass"];
            string newPass = Request.Form["password"];
            bool success = AccountModel.changePassword(Session["username"].ToString(), oldPass, newPass);
            if (success)
            {
                return RedirectToAction("personal", "Account");
            }

            ViewBag.nameMsg = "Đổi mật khẩu";
            ViewBag.bodyMsg = "Mật khẩu cũ không chính xác!";
            return View("ShowInfo");
        }

        /* Trả về số lượng có trong kho nếu thất bại*/
        [HttpPost]
        public int addToCart()
        {
            try
            {
                int id = Int32.Parse(Request.Form["id"]);
                int quantity = Int32.Parse(Request.Form["quantity"]);
                int capacity = AccountModel.getCapacity(id);
                Dictionary<int, int> cart = (Dictionary<int, int>)Session["cart"];
                if (cart == null)
                {
                    cart = new Dictionary<int, int>();
                }
                if (cart.ContainsKey(id))
                {
                    if (cart[id] + quantity > capacity) { return capacity; }
                    cart[id] = cart[id] + quantity;
                }
                else
                {
                    if (quantity > capacity) { return capacity; }
                    cart.Add(id, quantity);
                }
                Session["cart"] = cart;
            }
            catch (Exception) { }
            return -1;
        }

        public ActionResult Cart()
        {
            Dictionary<int, int> cart = (Dictionary<int, int>)Session["cart"];
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            if (cart != null)
            {
                //create empty list
                var proList = (from p in ctx.Products
                               where p.ID == 0
                               select p);
                //add each product to list
                foreach (var pro in cart)
                {
                    var product = (from p in ctx.Products
                                   where pro.Key == p.ID
                                   select p);
                    proList = proList.Union(product);
                }
                //remove old promotion
                foreach (var rs in proList)
                {
                    if (rs.promotion_ID.HasValue)
                    {
                        if (System.DateTime.Now < rs.Promotion.start_date || rs.Promotion.end_date < System.DateTime.Now)
                        {
                            rs.Promotion = null;
                        }
                    }
                }
                ViewBag.proList = proList;
                ViewBag.cart = cart;
            }

            return View();
        }

        public ActionResult cartHandler()
        {
            var action = Request.Form["Action"];
            if ("Cập nhật số lượng".Equals(action))
            {
                Dictionary<int, int> cart = (Dictionary<int, int>)Session["cart"];
                if (cart != null)
                {
                    var keys = Request.Form.AllKeys;
                    foreach (var key in keys)
                    {
                        if (key.Contains("quantity"))
                        {
                            string id = key.Substring(9);
                            int proID = 0;
                            try
                            {
                                proID = Int32.Parse(id);
                            }
                            catch (Exception) { }
                            if (cart.ContainsKey(proID))
                            {
                                string qt = Request.Form[key];
                                int quantity = 0;
                                try
                                {
                                    quantity = Int32.Parse(qt);
                                }
                                catch (Exception) { }
                                if (quantity > 0)
                                {
                                    cart[proID] = quantity;
                                }
                                else
                                {
                                    cart.Remove(proID);
                                }
                            }
                        }
                    }
                    if (cart.Count == 0)
                    {
                        cart = null;
                    }
                    Session["cart"] = cart;
                }
            }
            else if ("Xóa giỏ hàng".Equals(action))
            {
                Session["cart"] = null;
            }
            else if ("Đặt mua & Thanh toán".Equals(action))
            {
                return RedirectToAction("Checkout", "Account");
            }

            return RedirectToAction("Cart", "Account");
        }

        public ActionResult RemoveProduct(int proID)
        {
            Dictionary<int, int> cart = (Dictionary<int, int>)Session["cart"];
            if (cart != null)
            {
                cart.Remove(proID);
                if (cart.Count == 0)
                {
                    cart = null;
                }
                Session["cart"] = cart;
            }
            return RedirectToAction("Cart", "Account");
        }

        public ActionResult MiniCart()
        {
            Dictionary<int, int> cart = (Dictionary<int, int>)Session["cart"];
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            if (cart != null)
            {
                //create empty list
                var proList = (from p in ctx.Products
                               where p.ID == 0
                               select p);
                //add each product to list
                foreach (var pro in cart)
                {
                    var product = (from p in ctx.Products
                                   where pro.Key == p.ID
                                   select p);
                    proList = proList.Union(product);
                }
                //remove old promotion
                foreach (var rs in proList)
                {
                    if (rs.promotion_ID.HasValue)
                    {
                        if (System.DateTime.Now < rs.Promotion.start_date || rs.Promotion.end_date < System.DateTime.Now)
                        {
                            rs.Promotion = null;
                        }
                    }
                }
                ViewBag.proList = proList; //foreach (var p in proList) {p.category_ID }
                ViewBag.cart = cart;
            }

            return View();
        }

        [CustomAuthorization(UserLevel = new int[] { 2 })]
        public ActionResult Checkout()
        {

            if (Response.StatusCode == 401)
            {
                RouteValueDictionary data = new RouteValueDictionary();
                data.Add("GotoAction", "Cart");
                data.Add("GotoConntroller", "Account");
                return RedirectToAction("Login", "Account", data);
            }
            if (Session["cart"] == null)
            {
                return RedirectToAction("Index2", "Main");
            }
            bool success = AccountModel.checkout(Session["username"].ToString(), (Dictionary<int, int>)Session["cart"]);
            if (success)
            {
                Session["cart"] = null;
                ViewBag.nameMsg = "Đặt hàng thành công";
                ViewBag.bodyMsg = "<font color='black'>Cám ơn bạn đã sử dụng dịch vụ của chúng tôi <br/>Chúng tôi sẽ gọi xác nhận trong vòng</font> 30 phút <font color='black'>vào giao hàng</font> 30 phút <font color='black'>kể từ khi xác nhận đơn hàng này</font>";
            }
            else
            {
                ViewBag.nameMsg = "Đặt hàng thất bại";
                ViewBag.bodyMsg = "<font color='black'>Có lỗi trong quá trình đặt hàng</font> </br> Xin quý khách vui lòng thử lại";
            }
            return View("ShowInfo");
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult CustomerOrderList(int accID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }

            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var orderList = (from o in ctx.Orders
                             orderby o.order_date descending
                             where o.customer_ID == accID
                             select o);
            ViewBag.orderList = orderList.Count() > 0 ? orderList : null;
            return View(accID);
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult CustomerRemoveOrder(int accID, int orderID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }

            bool success = AccountModel.removeOrder(orderID);
            if (success) { }
            var level = new int[] { 0, 1 };
            if (level.Contains((int)Session["userLevel"]))
            {
                return RedirectToAction("adminOrderList", "Admin");
            }
            RouteValueDictionary data = new RouteValueDictionary();
            data.Add("accID", accID);
            return RedirectToAction("CustomerOrderList", "Account", data);
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult CustomerOrderDetailList(int orderID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var orderDetailList = (from od in ctx.Order_Details
                                   where od.order_ID == orderID
                                   select od);
            ViewBag.orderDetailList = orderDetailList.Count() > 0 ? orderDetailList : null;
            var order = (from o in ctx.Orders
                         where o.ID == orderID
                         select o).SingleOrDefault();
            ViewBag.order = order;
            return View();
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult CustomerOrderDetailListClick()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            int orderID = 0;
            try
            {
                orderID = Int32.Parse(Request.Form["hiddenOrderID"]);
            }
            catch (Exception e) { }
            bool success = true;
            string action = Request.Form["btnSubmit"];
            if ("Cập nhật số lượng".Equals(action))
            {
                Dictionary<int, int> tmpOrder = new Dictionary<int, int>();
                var keys = Request.Form.AllKeys;
                foreach (var key in keys)
                {
                    if (key.Contains("quantity"))
                    {
                        string id = key.Substring(9);
                        int odID = 0;
                        try
                        {
                            odID = Int32.Parse(id);
                        }
                        catch (Exception) { }

                        string qt = Request.Form[key];
                        int quantity = 0;
                        try
                        {
                            quantity = Int32.Parse(qt);
                        }
                        catch (Exception) { }
                        tmpOrder.Add(odID, quantity);
                    }
                }
                success = AccountModel.updateQuantityOrderDetail(tmpOrder, orderID);
            }

            if (success)
            {
                RouteValueDictionary data = new RouteValueDictionary();
                data.Add("orderID", orderID);
                return RedirectToAction("CustomerOrderDetailList", "Account", data);
            }
            return RedirectToAction("personal", "Account");
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult CustomerRemoveOrderDetail(int accID, int orderID, int orderDetailID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }

            bool success = AccountModel.removeOrderDetail(orderDetailID);
            RouteValueDictionary data = new RouteValueDictionary();
            if (!success)
            {
                var level = new int[] { 0, 1 };
                if (level.Contains((int)Session["userLevel"]))
                {
                    return RedirectToAction("adminOrderList", "Admin");
                }
                data.Add("accID", accID);
                return RedirectToAction("CustomerOrderList", "Account", data);
            }
            data.Add("orderID", orderID);
            return RedirectToAction("CustomerOrderDetailList", "Account", data);
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult CustomerAddCartToOrder(int orderID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            Dictionary<int, int> cart = (Dictionary<int, int>)Session["cart"];
            bool success = AccountModel.addCartToOrder(orderID, cart);
            RouteValueDictionary data = new RouteValueDictionary();
            if (!success)
            {
                var level = new int[] { 0, 1 };
                if (level.Contains((int)Session["userLevel"]))
                {
                    return RedirectToAction("adminOrderList", "Admin");
                }
                data.Add("accID", (int)Session["accID"]);
                return RedirectToAction("CustomerOrderList", "Account", data);
            }
            Session["cart"] = null;
            data.Add("orderID", orderID);
            return RedirectToAction("CustomerOrderDetailList", "Account", data);
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult AccountInfo(string username)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var acc = ctx.Accounts.Where(a => a.username == username).SingleOrDefault();
            return View(acc);
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult AccountInfoClick(string username, string password, string fullName,
            string email, string address, string phoneNum)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            AdminModel.saveAccount(username, password, fullName, email, address, phoneNum);

            return RedirectToAction("personal", "Account");
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult addWishlist(int proID, string username)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "personal";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AccountModel.saveWishlist(proID, username);
            if (success) { }
            return RedirectToAction("MiniWishlist", "Account");
        }

        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult WishlistView()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "WishlistView";
                ViewBag.controller = "Account";
                return View("Login");
            }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var user = ctx.Accounts.Where(a => a.username == Session["username"]).SingleOrDefault();
            if (user == null) { return View("Login"); }
            var wishlist = ctx.Wishlists.Where(w => w.customer_ID == user.ID);
            if (wishlist.Count() == 0) { wishlist = null; }
            return View(wishlist); //foreach (var w in wishlist) {w. }
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult deleteAllWishlist()
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "WishlistView";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AccountModel.deleteAllWishlist((string)Session["username"]);
            if (success) { }
            return RedirectToAction("WishlistView", "Account");
        }

        [HttpPost]
        [CustomAuthorization(UserLevel = new int[] { 0, 1, 2 })]
        public ActionResult deleteWishlist(int proID)
        {
            if (Response.StatusCode == 401)
            {
                Response.StatusCode = 200;
                ViewBag.action = "WishlistView";
                ViewBag.controller = "Account";
                return View("Login");
            }
            bool success = AccountModel.deleteWishlist((string)Session["username"], proID);
            if (success) { }
            return RedirectToAction("WishlistView", "Account");
        }

        public ActionResult MiniWishlist()
        {
            var username = Session["username"];
            if (username == null) { return View(); }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var user = ctx.Accounts.Where(a => a.username == username.ToString()).SingleOrDefault();
            if (user == null) { return View(); }
            var wishlist = ctx.Wishlists.Where(w => w.customer_ID == user.ID);
            if (wishlist.Count() == 0) { return View(); }
            return View(wishlist);
        }
    }
}
